package com.news.sentiment.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.news.sentiment.annotation.CheckToken;
import com.news.sentiment.enums.ResultEnum;
import com.news.sentiment.pojo.User;
import com.news.sentiment.service.UserService;
import com.news.sentiment.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("Authentication");

        //如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(CheckToken.class)){
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            if(checkToken.required()){
                if(token == null){
                    responseMessage(response,Result.fail(ResultEnum.AUTHENTICSTION_ERROR));
                    return false;
                }
                String userid = JWT.decode(token).getClaim("userid").asString();
                String password = JWT.decode(token).getClaim("password").asString();
                User user = userService.findByUserid(userid);
                if(user == null){
                    responseMessage(response, Result.fail(ResultEnum.AUTHENTICSTION_ERROR));
                    return false;
                }
                if(!(user.getPassword().equals(password))){
                    responseMessage(response,Result.fail(ResultEnum.AUTHENTICSTION_ERROR));
                    return false;
                }


            }
        }
        return true;

    }

    private void responseMessage(HttpServletResponse response,Result result) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String jsonString = JSON.toJSONString(result);
        System.out.println(jsonString);
        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        writer.flush();
        writer.close();
    }
}
